<template>
  <!-- 配送员轨迹 -->
  <div class="main">
    <baidu-map
      class="map"
      :center="center"
      :zoom="zoom"
      :scroll-wheel-zoom="true"
      @ready="handler"
    >
      <bm-map-type :map-types="['BMAP_NORMAL_MAP', 'BMAP_HYBRID_MAP']" anchor="BMAP_ANCHOR_TOP_RIGHT" />
      <bm-scale anchor="BMAP_ANCHOR_BOTTOM_LEFT" />
      <div v-show="run === 1">
        <bm-marker v-for="(item,index) in gasmanOrder1" :key="index" :position="{lng: item.lon, lat: item.lat}" @click="look(item)">
          <bm-label
            :content="index + 1 + ''"
            :label-style="labelStyle"
            :offset="{width: 2, height: 2}"
          />
        </bm-marker>
        <bm-polyline :path="lineList" stroke-color="blue" :stroke-opacity="0.5" :stroke-weight="2" />
        <bml-lushu
          :path="lineList"
          :icon="icon"
          :play="play"
          :speed="200"
        />
      </div>
      <!-- 订单信息 -->
      <bm-info-window :position="position02" :show="show02" @close="infoWindowClose" @open="infoWindowOpen">
        <el-descriptions :column="1" :v-model="from">
          <el-descriptions-item label="订单号">{{ from.orderCode }}</el-descriptions-item>
          <el-descriptions-item label="客户编号">{{ from.csmCode }}</el-descriptions-item>
          <el-descriptions-item label="联系人">{{ from.csmName }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ from.csmPhone }}</el-descriptions-item>
          <el-descriptions-item label="地址">{{ from.csmAddress }}</el-descriptions-item>
          <el-descriptions-item label="商品描述">{{ from.goodsDesc }}</el-descriptions-item>
          <el-descriptions-item label="签收时间">{{ from.modifyTime?parseTime(from.modifyTime, '{y}-{m}-{d} {h}:{i}:{s}'):'' }}</el-descriptions-item>
        </el-descriptions>
      </bm-info-window>
    </baidu-map>

    <div ref="right" class="right">
      <span style="display: inline-block; margin-bottom: 10px;">配送员列表</span>
      <i class="el-icon-d-arrow-right" @click="fold('right')" />
      <el-card class="rightCard">
        <el-form ref="form" :model="submit" label-width="80px" style="padding: 5px;">
          <el-form-item class="merge-item" label="查询日期:">
            <el-date-picker
              v-model="submit.signDate"
              type="date"
              :clearable="false"
              placeholder="选择日期时间"
            />
          </el-form-item>
          <el-form-item label="组织机构:" prop="orgSNNo">
            <el-tree-select
              v-model="submit.orgSNNo"
              clearable
              class="tree-select"
              :popover-width="360"
              :select-params="{
                clearable: true,
                placeholder: '请选择',
                loading: $loadingPlugin.getTreeData
              }"
              :tree-params=" {
                'expand-on-click-node': false,
                'highlight-current': true,
                props:{
                  value:'orgSNNo',
                  label: 'orgName',
                  disabled: 'disabled',
                },
                data: treeData
              }"
              @node-click="selectTreeChange"
            />
          </el-form-item>
          <el-form-item label="姓名:">
            <el-input v-model.trim="submit.userName" style="width: 120px;" />
            <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
          </el-form-item>
          <lb-table
            ref="lbTable"
            v-el-height-adaptive-table="{bottomOffset:10}"
            class="table"
            border
            highlight-current-row
            element-loading-text="加载中"
            :column="tableData.column"
            :data="tableData.data"
            :total="tableData.total"
            custom-column
            style="overflow: auto;"
            @row-click="handleCurrentChange1"
          />
        </el-form>
      </el-card>

      <!-- 配送单 -->
      <el-collapse v-show="run === 1 && gasmanOrder1.length > 0" class="orderListPage" :value=" gasmanOrder1.length>0 ? 1 : 0">
        <el-collapse-item :title="` 共找到${gasmanOrder1.length}个结果`" :name="1">
          <lb-table
            ref="lbTable"
            class="table021"
            border
            element-loading-text="加载中"
            :column="tableData02.column"
            :data="tableData02.data"
            :total="tableData02.total"
            custom-column
            max-height="400"
            style="overflow: auto;"
            @current-change="handleCurrentChange"
          />
        </el-collapse-item>
      </el-collapse>

    </div>
  </div>
</template>

<script>
  // import allgasman from './allgasman.json'
  // import gasmanOrder from './gasmanOrder.json'
  // import trackRectify from './trackRectify.json'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  // import dayjs from 'dayjs'
  import { parseTime } from '@/utils'
  import { BmlLushu } from 'vue-baidu-map'
  import { companySetting, trackAllgasman, trackGasmanOrder, trackTrackRectify } from '@/api'
  export default {
    name: 'deliveryTrack',
    components: {
      BmlLushu
    },
    data() {
      return {
        labelStyle: { color: '#fff', fontSize: '12px', background: 'rgba(0, 0, 0, 0)', borderColor: 'rgba(0, 0, 0, 0)' },
        play: true,
        title: 15,
        icon: {
          // url: '../../../assets/map_images/gasman2.png',
          url: require('../../../assets/map_images/gasman2.png'),
          // url: 'http://api.map.baidu.com/library/LuShu/1.2/examples/car.png',
          size: { width: 40, height: 45 },
          opts: { anchor: { width: 10, height: 13 }}
        },
        submit: {
          'userName': null,
          'signDate': new Date(),
          'orgSNNo': null
        },
        show: false,
        run: 2,
        show02: false,
        from: {},
        position: { lng: 0, lat: 0 },
        position02: { lng: 0, lat: 0 },
        center: { lng: 0, lat: 0 },
        lineList: [],
        zoom: 14,
        BMap: {},
        map: {},
        txt: '',
        ids: [],
        qtype: 1,
        treeData: [],
        query: {},
        tableData: {
          total: 0,
          column: [
            {
              type: 'index',
              align: 'center',
              width: 80
            },
            {
              prop: 'userName',
              label: '姓名',
              render: (h, { row }) =>
              <div onClick={() => this.getlocation(row)}>
                {row.userName}
              </div>
            }
          ],
          data: []
        },
        tableData02: {
          total: 0,
          column: [
            {
              type: 'index',
              align: 'center',
              width: 30
            },
            {
              label: '信息',
              align: 'left',
              render: (h, { row }) =>
              <div style=' white-space: normal !important;' class='tableInfo'>
                <div style=' white-space: normal !important;'>{row.csmAddress}</div>
                <div style=' white-space: normal !important;'>{row.modifyTime ? parseTime(row.modifyTime, '{y}-{m}-{d} {h}:{i}:{s}') : ''}</div>
              </div>
            }
          ],
          data: []
        },
        // 配送员订单
        gasmanOrder1: [],
        // 轨迹
        trackRectify1: []
      }
    },
    computed: {
      ...mapGetters([
        'orgList'
      ])
    },
    created() {
      this.getTreeData()
      this.search()
    },
    mounted() {

    },
    methods: {
      parseTime,
      async handler({ BMap, map }) {
        const _this = this
        this.zoom = 15
        this.BMap = BMap
        this.map = map
        const res = await companySetting()
        let currentCity = ''
        if (res.data.rows && res.data.rows.length > 0 && res.data.rows[0].city && res.data.rows[0].city !== '') currentCity = res.data.rows[0].city
        if (currentCity !== '') {
          map.centerAndZoom(currentCity, 14)
        } else {
          const localCity = new BMap.LocalCity()
          localCity.get(function(result) {
            const cityName = result.name
            map.centerAndZoom(cityName, _this.zoom)
          })
        }
      },
      infoWindowClose() {
        this.show = false
      },
      infoWindowOpen() {
        this.show = true
      },
      // 折叠效果
      fold(refItem) {
        const classname = event.target.className
        const flag = classname.includes('right')
        if (flag) {
          event.target.className = 'el-icon-d-arrow-left'
        } else {
          event.target.className = 'el-icon-d-arrow-right'
        }
        var width = this.$refs[refItem].style.width
        if (width === '20px') {
          this.$refs[refItem].style.width = '300px'
          this.$refs[refItem].childNodes[0].style.display = 'block'
          this.$refs[refItem].childNodes[4].style.display = 'block'
        } else {
          this.$refs[refItem].style.width = '20px'
          this.$refs[refItem].childNodes[0].style.display = 'none'
          this.$refs[refItem].childNodes[4].style.display = 'none'
        }
      },
      // 点击图标
      look(item) {
        this.from = item
        this.content = item.name
        this.position02.lng = item.lon
        this.position02.lat = item.lat
        this.show02 = true
      },
      getlocation(row) {
        if (!row) {
          this.$message({
            message: '没有查询到相关数据',
            type: 'warning'
          })
        } else {
          this.position.lat = row.lat
          this.position.lng = row.lon
          this.center = this.position
          this.show = true
          this.run = 1
        }
      },
      async handleCurrentChange1(row) {
        this.map.clearOverlays()
        const params = {
          date: parseTime(this.submit.signDate, '{y}-{m}-{d} {h}:{i}:{s}'),
          // date: (this.submit.signDate*1/1000).toString(),
          userId: row.userId
        }
        const res = await trackGasmanOrder(params)
        this.gasmanOrder1 = []
        this.tableData02.data = []
        await this.trackRectify()
        this.gasmanOrder1 = res.data.rows.reverse()
        if (this.gasmanOrder1.length === 0) this.$message.info('没有查询到相关数据')
        this.tableData02.data = res.data.rows
        await this.trackRectify(res.data.rows)
      },
      async trackRectify(orderList, callback) {
        if (!orderList || orderList.length === 0) {
          return
        }
        orderList.reverse()
        var array = []
        var firstLocateTime = 0
        for (var i = 0; i < orderList.length; i++) {
          var p = orderList[i]
          if (!p || !p.lon || !p.lat || p.lon < 0 || p.lon > 180 || p.lat < 0 || p.lat > 180 || p.lon === 4.9E-324 || p.lat === 4.9E-324) {
            continue
          }
          // 超过5分钟，会被认为定位中断。中断后百度不会进行坐标补偿，所以设置定位时间为3分钟
          if (firstLocateTime === 0) {
            firstLocateTime = this.parseDate(p.signDt).getTime()
          } else {
            firstLocateTime += 3 * 60 * 1000
          }
          var time = '' + firstLocateTime
          time = time.substring(0, time.length - 3)

          array.push({
            latitude: p.lat,
            longitude: p.lon,
            coord_type_input: 'bd09ll',
            loc_time: time,
            // speed: 10,
            radius: 7
          })
        }
        const params = {
          pointList: array,
          transport_mode: 'riding'
        }
        const rlt = await trackTrackRectify(params)
        this.lineList = []
        if (rlt) {
          console.log('纠偏结果', rlt)
          array = []
          JSON.parse(rlt.data).forEach(function(p) {
            var point = new window.BMap.Point(p.longitude, p.latitude)
            array.push(point)
          })
          this.trackRectify1 = JSON.parse(rlt.data)
          this.poly()
        }
      },
      parseDate(str) {
        if (/^([0-9]{2,4})-([0-9]{1,2})-([0-9]{1,2})T([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}).([0-9]{1,3})\+(0800)$/.test(str)) {
          return new Date(str)
        }
        str = String(str).replace(/-/g, '/').replace('Z', '').replace('T', ' ')
        if (str.indexOf('.') > 0) {
          var dd = str.split('.')
          var d = new Date(dd[0])
          d.setMilliseconds(dd[1])
          return d
        }
        return new Date(str)
      },
      async search() {
        const params = {
          ...this.submit
        }
        if (!params.signDate) {
          this.$message.error('请选择查询日期')
          return
        }
        const res = await trackAllgasman(params)
        this.tableData.data = res.data
      },
      // 获取所属机构数据
      async getTreeData() {
        // const res = await organizationQueryList({})
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.orgSNNo = value.orgSNNo
      },
      // 折线
      poly() {
        var newArr = JSON.parse(JSON.stringify(this.trackRectify1))

        for (let i = 0; i < newArr.length; i++) {
          if (i === 0) {
            var point = new this.BMap.Point(newArr[0].longitude, newArr[0].latitude)
            // console.log(this.map)
            this.map.centerAndZoom(point, 20)
          }
          var objArr = []
          objArr.lng = newArr[i].longitude
          objArr.lat = newArr[i].latitude
          this.lineList.push(objArr)
        }
      },
      // 获取选中
      handleCurrentChange(val) {
        this.position02.lat = val.lat
        this.position02.lng = val.lon
        var point = new this.BMap.Point(val.lon, val.lat)
        // console.log(this.map)
        this.map.centerAndZoom(point, 20)
        this.show02 = true
        this.from = val
      }
    }
  }
</script>

<style lang='scss' scoped>
.main {
  display: flex;
  height: 100%;
  font-size: 14px;
  /deep/ .el-table .el-table__body tr {
    cursor: pointer;
  }
  .el-form-item {
    margin-bottom: 10px;
  }
  .tableInfo {
    font-size: 14px;
    font-weight: 500;
  }
  .map {
    position: relative;
    width: 100%;
    height: 100%;
    // .bmLabel{
    //   background-color: transparent;
    //   color: black;
    //   font-weight: 700;
    //   font-size: 16px;
    //   border: 0;
    // }
    .label-style {
      font-size: 12px;
      color: #fff;
      background: rgba(0, 0, 0, 0);
      border-color: rgba(0, 0, 0, 0);
    }

    /deep/ .el-descriptions-item__label {
      width: 70px;
    }
  }

  .right {
    position: relative;
    width: 300px;
    height: 100%;
    padding: 4px;
    font-size: 14px;
    // font-weight: bold;
    // color: #777;
    transition: all 0.3s;
    /deep/ .el-collapse-item__header {
      text-indent: 5px;
    }
    i {
      position: absolute;
      top: 3px;
      right: 0;
      cursor: pointer;
    }

    .orderListPage {
      position: absolute;
      top: 70px;
      left: -240px;
      width: 240px;
      height: 400px;
      transition: all 0.3s;

      i {
        position: absolute;
        top: 13px;
        right: 0;
      }

      .listTop {
        height: 40px;
        line-height: 40px;
        background-color: #fff;
      }

      /deep/ .el-card__body {
        padding: 0;
      }

      .table02 {
        height: 350px;
      }
    }

    .rightCard {
      height: calc(100% - 22px);

      /deep/ .el-card__body {
        padding: 0;
      }
      /deep/ .el-card__header {
        height: 24px;
        padding: 0 10px;
        font-size: 14px;
        font-weight: bold;
        // padding: 0;
        line-height: 24px;
        color: #373A3C;
        background: #e3e3e3;
        border: 1px solid #ddd;
        box-sizing: border-box;
      }
    }
  }
}

</style>
